package br.edu.utfpr.md.tads.resources;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;

import br.edu.utfpr.md.tads.data.ContatosData;
import br.edu.utfpr.md.tads.model.Contato;

@Path(value="contatos")
public class ListaTelefonicaResource {

	   @Context
	    UriInfo uriInfo;

	    @Context
	    Request request;

	    @GET
	    @Produces({MediaType.TEXT_PLAIN})
	    public List<Contato> getLista(){	        
	        List<Contato> contatos = new ArrayList<>();
	        contatos.addAll(ContatosData.instance.getContatos().values());
	        return contatos;
	    }
	    
	    @GET
	    @Path("/busca")
	    @Produces({MediaType.TEXT_PLAIN})
	    public List<Contato> getListaBuscaPlain(String busca){	        
	        List<Contato> contatos = new ArrayList<>();
	        contatos.addAll(ContatosData.instance.busca(busca).values());
	        return contatos;
	    }
	    
	    @GET
	    @Path("/busca/{busca}")
	    @Produces({MediaType.APPLICATION_JSON})
	    public List<Contato> getListaBusca(@PathParam("busca") String busca){	        
	        return getListaBuscaPlain(busca);
	    }
	    
	    @GET
		@Produces(MediaType.APPLICATION_JSON)
		@Path("/json")
	    public List<Contato> getListaJson(){
	        return getLista();
	    }
		      
	    @GET
		@Produces(MediaType.APPLICATION_XML)
		@Path("/xml")
	    public List<Contato> getListaXml(){
	        return getLista();
	    }
	    
	    @POST
		@Consumes(MediaType.APPLICATION_XML)
	    @Path("/crud/xml")
		public Response insertContatoXml(JAXBElement<Contato> contatos) {
			Response response;
			Contato contato = contatos.getValue();
			if (ContatosData.instance.insert(contato)) {
				response = Response.ok().build();
			} else {
				response = Response.ok().build();
			}
			return response;
		}
	    @POST
		@Consumes(MediaType.APPLICATION_JSON)
	    @Path("/json")
		public Response insertContatoJson(JAXBElement<Contato> contatos) {
			Response response;
			Contato contato = contatos.getValue();
			if (ContatosData.instance.insert(contato)) {
				response = Response.ok().build();
			} else {
				response = Response.ok().build();
			}
			return response;
		}
	    
	    @Path("/crud/{contato}")
	    public ContatoResource getContatos(@PathParam("contato") String id){
	    	return new ContatoResource(uriInfo,request,id);
	    }
}
